import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:test_flutter/cache/UserDataCache.dart';
import 'package:test_flutter/dio/Api.dart';
import 'package:test_flutter/pages/LoginPage.dart';

class DioUtil {
  static DioUtil instance;
  static Dio dio;
  static BaseOptions options;
  static BuildContext context;
  static DioUtil getInstance(BuildContext mContext) {
    if (instance == null) {
      instance = new DioUtil();
    }
    context = mContext;
    return instance;
  }

  DioUtil() {
    // 或者通过传递一个 `options`来创建dio实例
    options = BaseOptions(
      baseUrl: Api.baseUrl,
      connectTimeout: 8000,
      receiveTimeout: 8000,
      headers: {},
    );
    dio = new Dio(options);
  }

  ///post请求
  post(url, Function callBack,
      {data, Function errorCallBack, cancelToken, bool hasToken = true}) async {
    print('post请求启动! url：$url ,body: $data');

    Response response;
    String errorMsg = "";
    int statusCode;
    if (hasToken) {
      String token = await UserDataCache.getInstance().getToken();
      options.headers['Authorization'] = "Bearer $token";
      print('header数据：${options.headers}');
    } else {
      options.headers['Authorization'] = "";
    }
    try {
      response = await dio.post(
        url,
        data: data,
        cancelToken: cancelToken,
      );
      statusCode = response.statusCode;
      print("<net==============> response data:  $statusCode");
      //处理错误部分
      if (statusCode < 0) {
        errorMsg = "网络请求错误,状态码:" + statusCode.toString();
        _handError(errorCallBack, errorMsg);
        return;
      }
      if (callBack != null) {
        print('post请求成功!response.data：${response.data}');
        callBack(response);
      }
    } on DioError catch (exception) {
      if(exception.message.indexOf("401") != -1){
        await UserDataCache.getInstance().loginOut();
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (context) => LoginPage('登录页')),
                (Route<dynamic> rout) => false);
      }else{
        _handError(errorCallBack, exception.message);
      }
    }
  }

  ///get 请求
  get(url, Function callBack,
      {Map<String, dynamic>  data, Function errorCallBack, cancelToken, bool hasToken = true}) async {
    print('get请求启动! url：$url ,body: $data');

    Response response;
    String errorMsg = "";
    int statusCode;
    if (hasToken) {
      String token = await UserDataCache.getInstance().getToken();
      options.headers['Authorization'] = "Bearer $token";
      print('header数据：${options.headers}');
    } else {
      options.headers['Authorization'] = "";
    }
    try {
      response = await dio.get(
        url,
        queryParameters: data,
        cancelToken: cancelToken,
      );
      statusCode = response.statusCode;
      print("<net==============> response data:  $statusCode");
      //处理错误部分
      if (statusCode < 0) {
        errorMsg = "网络请求错误,状态码:" + statusCode.toString();
        _handError(errorCallBack, errorMsg);
        return;
      }
      if (callBack != null) {
        print('get请求成功!response.data：+${response.request.path}+${response.data}');
        callBack(response);
      }
    } on DioError catch (exception) {
      if(exception.message.indexOf("401") != -1){
        await UserDataCache.getInstance().loginOut();
        Navigator.of(context).pushAndRemoveUntil(
            MaterialPageRoute(builder: (context) => LoginPage('登录页')),
                (Route<dynamic> rout) => false);
      }else{
        _handError(errorCallBack, exception.message);
      }

    }
  }

  ///上传文件
  uploadFile(String url,FormData formData,Function callBack,{data, Function errorCallBack, cancelToken, bool hasToken = true}) async{
    Response response;
    String errorMsg = "";
    int statusCode;
    if (hasToken) {
      String token = await UserDataCache.getInstance().getToken();
      options.headers['Authorization'] = "Bearer $token";
      print('header数据：${options.headers}');
    } else {
      options.headers['Authorization'] = "";
    }
    try {
      response = await dio.post(
        url,
        data: formData,
        cancelToken: cancelToken,
        onSendProgress: (int sent, int total) {
          print("$sent $total");
        }
      );
      statusCode = response.statusCode;
      print("<net==============> response data:  $statusCode");
      //处理错误部分
      if (statusCode < 0) {
        errorMsg = "网络请求错误,状态码:" + statusCode.toString();
        _handError(errorCallBack, errorMsg);
        return;
      }
      if (callBack != null) {
        print('Post上传文件请求成功!response.data：${response.data}');
        callBack(response);
      }
    } on DioError catch (exception) {
      _handError(errorCallBack, exception.message);
    }


  }

  //处理异常
  static void _handError(Function errorCallback, String errorMsg) {
    if (errorCallback != null) {
      errorCallback(errorMsg);
    }
    print("<net> errorMsg :" + errorMsg);
  }
}

